// pages/cart/index.js
import { getSetting, chooseAddress, openSetting, showModal, showToast } from '../../utils/asyncWx'
import regeneratorRuntime from '../../lib/runtime/runtime';

Page({

  data: {
    // 收货地址
    address: {},
    // 购物车商品
    cart: [],
    // 全选框
    allChecked: true,
    // 总价格
    totalPrice: 0,
    // 总数量
    totalNum: 0
  },

  onShow: function (options) {
    const address = wx.getStorageSync("address");
    const cart = wx.getStorageSync("cart") || [];

    this.setCart(cart)

    this.setData({
      address
    })
  },

  // 修改收货地址 
  async handleChooseAddress () {

    // wx.getSetting({
    //   success: (result) => {
    //     const scopeAddress = result.authSetting["scope.address"]
    //     if (scopeAddress === true || scopeAddress === undefined) {
    //       wx.chooseAddress({
    //         success: (result1) => {
    //           console.log(result1);
    //         }
    //       })
    //     } else {
    //       wx.openSetting({
    //         success: (result2) => {
    //           console.log(result2);
    //           wx.chooseAddress({
    //             success: (result3) => {
    //               console.log(result3);
    //             }
    //           })
    //         },
    //       });
    //     }
    //   }
    // });

    try {
      const res1 = await getSetting()
      const scopeAddress = res1.authSetting["scope.address"]
      if (scopeAddress === false) {
        await openSetting()
      }

      let address = await chooseAddress()

      // 总地址
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo

      // 把获取到的地址存到本地存储中
      wx.setStorageSync("address", address);


    } catch (error) {
      console.log(error);
    }

  },

  // 商品选中
  handleChecked (e) {
    // 1 获取商品id
    const goods_id = e.currentTarget.dataset.id
    // console.log(goods_id);

    // 2 获取购物车商品数组
    const cart = this.data.cart

    // 3 获取对应的商品索引
    const index = cart.findIndex(v => v.goods_id === goods_id)

    // 4 对复选框取反
    cart[index].checked = !cart[index].checked

    this.setCart(cart)

  },

  // 全选反选
  handleAllChecked () {
    let { cart, allChecked } = this.data

    // 对全选框取反
    allChecked = !allChecked

    // 遍历  复选框 = 全选框的状态
    cart.forEach(v => v.checked = allChecked)

    this.setCart(cart)
  },

  // 商品数量的增减
  async handleNumEdit (e) {

    // 1 获取定义的属性参数
    const { id, operation } = e.currentTarget.dataset
    // 2 获取购物车数组
    let { cart } = this.data
    // 3 获取要修改商品的索引
    const index = cart.findIndex(v => v.goods_id === id)
    // 4 当数量为一且继续点击 -  弹框提示是否要删除
    if (cart[index].num === 1 && operation === -1) {
      // 弹框提示
      const res = await showModal({ content: "确认要删除嘛" })
      // 确认删除
      if (res.confirm) {
        // 删除购物车数组对应的商品
        cart.splice(index, 1)
      }
    } else {
      // 5 修改商品的数量
      cart[index].num += operation
    }
    this.setCart(cart)

  },

  // 结算功能
  // 判断是否有收货地址和商品（总商品数量）
  async handlePay () {
    // 1 获取收货地址和商品数量
    const { address, totalNum } = this.data
    // 2 判断是否有收货地址
    if (!address) {
      await showToast({ title: "选择收货地址!" })
      return
    }
    // 3 判断是否有商品
    if (!totalNum) {
      await showToast({ title: "选择商品!" })
      return
    }
    wx.navigateTo({
      url: '/pages/pay/index',
    })

  },

  // 设置购物车状态同时 重新计算 底部工具栏的数据 全选 总价格 购买的数量 
  setCart (cart) {
    let totalPrice = 0
    let totalNum = 0
    let allChecked = true

    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.goods_price * v.num
        totalNum += v.num
      } else {
        allChecked = false
      }
    })

    // 判断数组是否为空
    allChecked = cart.length ? allChecked : false

    this.setData({
      cart,
      totalPrice,
      totalNum,
      allChecked
    })

    wx.setStorageSync("cart", cart);

  }

})